package com.steven.download;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Parcelable;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.format.Formatter;
import android.util.Log;

import com.steven.download.download.DownloadFacade;
import com.steven.download.download.UnZipCallback;
import com.steven.download.download.db.DownloadEntity;
import com.steven.download.download.db.room.AppDataBase;
import com.steven.download.entity.DownRequestDate;
import com.steven.download.entity.JsonPathEntity;
import com.steven.download.entity.UninstallEntity;
import com.steven.download.net.Api;
import com.steven.download.utils.CPULevelUtils;
import com.steven.download.utils.DateUtil;
import com.steven.download.utils.SPUtils;
import com.steven.download.utils.SortUtil;
import com.steven.download.utils.StorageQueryUtil;
import com.steven.download.utils.ToastUtil;
import com.steven.download.utils.Utils;
import com.steven.download.utils.ZipFileUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_PERMISSION_CODE = 0x088;

    private Timer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BaseApplication.runBack = getIntent().getBooleanExtra("RUN_BACKGROUD", false);
        checkSelfPermission();
        initView();
        Log.e("ddd ", "kkkkkkkkkkkkkkkkkkk：");
        startTimerTask();


    }


    private void startTimerTask() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.e("ddd ", "定时任务任务管理：");
                if (Utils.isForeground(MainActivity.this)) {
                    Log.e("ddd ", "定时任务任务getJsonDate");
                    getJsonDate();
                }
            }
        }, DateUtil.getCurrentTo12Millis(), 24 * 60 * 60 * 1000);
//        }, 10*1000,20*1000);
    }





    @Override
    protected void onResume() {
        super.onResume();
    }

    private void getJsonDate() {
        /*
         **打印retrofit信息部分
         */
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Log.e("RetrofitLog", "retrofitBack = " + message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()//okhttp设置部分，此处还可再设置网络参数
                .addInterceptor(loggingInterceptor)
                .build();


        //构建Retrofit实例
        Retrofit mRetrofit = new Retrofit.Builder()
                //设置网络请求BaseUrl地址
                .baseUrl(AppConstant.DOWN_BASE_URL)
                //设置数据解析器
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //创建网络请求接口对象实例
        Api api = mRetrofit.create(Api.class);
        //对发送请求进行封装
        String lastSyncTime = SPUtils.getInstance().getString(AppConstant.LAST_SYNC_TIME);
        Call<DownRequestDate> dataCall = api.getJsonData(lastSyncTime, AppConstant.APP_ID);
        dataCall.enqueue(new Callback<DownRequestDate>() {
            @Override
            public void onResponse(Call<DownRequestDate> call, Response<DownRequestDate> response) {
                DownRequestDate body = response.body();
                if (body == null) return;
                if (body.getCode() == 0 && body.getData() != null) {
                    List<DownloadEntity> list = body.getData();
                    SortUtil.sortList(list, "updateAt", SortUtil.SORT_ASC);
                    Intent intent = new Intent(MainActivity.this, ListZipDownloadActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("list", (ArrayList<? extends Parcelable>) body.getData());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }

            }

            @Override
            public void onFailure(Call<DownRequestDate> call, Throwable t) {

            }
        });
    }

    private void initView() {
        findViewById(R.id.btn_single).setOnClickListener(v -> startActivity(new Intent(this, SingleDownloadActivity.class)));
        findViewById(R.id.btn_list).setOnClickListener(v -> startActivity(new Intent(this, ListDownloadActivity.class)));
        findViewById(R.id.btn_getdata).setOnClickListener(v -> getJsonDate());
        findViewById(R.id.btn_unzip).setOnClickListener(v -> unZip());
    }

    private void checkSelfPermission() {
        int isPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int isExternalPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int isCameraPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (isPermission == PackageManager.PERMISSION_DENIED && isExternalPermission == PackageManager.PERMISSION_DENIED
                && isCameraPermission == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
        } else {
            // 有三个类需要用户去关注，后面我们有可能会自己去更新代码，用户就需要换调用方式
            // 调用的方式 门面设计模式
            DownloadFacade.getFacade().init(this);

            getJsonDate();
        }
    }

    private void unZip() {
        List<DownloadEntity> entities = AppDataBase.getInstance(Utils.getContext()).getDownloadDao().queryAll();
        if (entities != null && entities.size() > 0) {
            for (int i = 0; i < entities.size(); i++) {
                if (!TextUtils.isEmpty(entities.get(i).getLocalPath())) {
                    ZipFileUtils.unzipFile(entities.get(i).getLocalPath(),
                            AppConstant.BOOK_UNZIP_DIR, AppConstant.IMG_UNZIP_DIR,
                            AppConstant.UNINSTALL, new UnZipCallback() {
                                @Override
                                public void onSuccess(String zipPath) {
                                    Log.e("test:", "解压文件：" + zipPath);
                                    ZipFileUtils.deleteUnInstalFile(zipPath);
                                }

                                @Override
                                public void onFailure(Exception e) {

                                }
                            });
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE && grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
                ToastUtil.toast(MainActivity.this, "需要存储权限");
            } else {
                DownloadFacade.getFacade().init(this);
                getJsonDate();
            }
        }
    }
}